// pages/today/today.js
const app = getApp()
const config = require('../../utils/config.js');
const auth = require('../../utils/auth.js');

Page({
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    babyId: 0,
    invitUserId: 0,
    babyName: '宝宝',
    userName: '用户',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userInfo: {},

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let babyId = options.babyId;
    let invitUserId = options.invitUserId;
    let babyName = options.babyName;
    let userName = options.userName;
    if (babyId != undefined) {
      this.setData({
        babyId: babyId,
        invitUserId: invitUserId,
        babyName: babyName,
        userName: userName,
      })
    }
    let sessionId = auth.checkDoLogin();
    this.setData({
      sessionId: sessionId,
    })
    let userInfo = wx.getStorageSync('userInfo');
    console.log(userInfo)
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  getUserInfo: function(e) {
    let that = this
    console.log(e)
    let userInfo = e.detail.userInfo;
    userInfo.isLogin = true;
    wx.setStorageSync('userInfo', userInfo);
    this.setData({
      userInfo: userInfo,
    })
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let param = {
          sessionId: that.data.sessionId,
          code: res.code,
        }
        console.log('微信登录请求：' + param)
        config.postApi(config.wxLogin, param).then((res) => {
          let newSessionId = res.sessionId
          wx.setStorageSync('sessionId', newSessionId);
          that.setData({
            sessionId: newSessionId,
          })
          //保存用户的信息
          config.postApi(config.addUserWxInfo, userInfo).then((res) => {
            //保存成功，接受邀请
            let accParam = { 
              babyId: that.data.babyId,
              invitUserId: that.data.invitUserId,
            }
            config.postApi(config.acceptInvit, accParam).then((res) => {
              //接受邀请成功，跳转首页
              wx.switchTab({
                url: '/pages/today/today',
              });
            }).catch((res) => {
              console.log(res)
              wx.switchTab({
                url: '/pages/today/today',
              });
            })


          }).catch((res) => {
            console.log(res)
          })
        }).catch((res) => {
          console.log(res)
        })
      }
    })

  },
})